package com.kwan.xframe.mvvm.data.source.http;

import android.os.Environment;

import com.kwan.xframe.api.BaseServerAPI;
import com.kwan.xframe.api.CountingRequestBody;
import com.kwan.xframe.util.ImageUtil;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;

import io.reactivex.rxjava3.core.Flowable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
import timber.log.Timber;

public class BaseHttpDataSource {

	public static String API_URL = "";

	protected HashMap<String, HttpRetrofitClient> map = new HashMap<>();

	protected HttpRetrofitClient getHttpRetrofitClient(String url, Map<String, String> header) {
		if (!map.containsKey(url)) {
			map.put(url, new HttpRetrofitClient(url, header));
		}
		return map.get(url);
	}

	protected HttpRetrofitClient getHttpRetrofitClient(String url, Map<String, String> header, HttpLoggingInterceptor.Level logLevel) {
		if (!map.containsKey(url)) {
			map.put(url, new HttpRetrofitClient(url, header).setLogLevel(logLevel));
		}
		return map.get(url);
	}

	public void refreshToken(String token, String url) {
		if (map.containsKey(url)) {
			Objects.requireNonNull(map.get(url)).setHeadValue(HttpRetrofitClient.TOKEN_KEY, "Bearer " + token);
		}
	}

	public enum UPLOAD_TYPE {
		FILE, IMAGE
	}

	/**
	 * 文件上传
	 *
	 * @param file        上传文件
	 * @param fileArgName 文件的参数名
	 * @param args        参数键值对 key---参数名 ，value--参数值
	 * @param listener
	 * @return
	 */

	public Flowable<HttpResult<Object>> uploadFile(UPLOAD_TYPE TYPE,
												   String url,
												   File file,
												   String fileArgName,
												   HashMap<String, String> args,
												   CountingRequestBody.Listener listener) {

		RequestBody requestBody = null;
		if (TYPE == UPLOAD_TYPE.FILE) {
			//构建文件的 part
			requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
		} else if (TYPE == UPLOAD_TYPE.IMAGE) {
			requestBody = RequestBody.create(MediaType.parse("image/*"), file);

			//图片 还要 进行压缩
			String targetPath = Environment.getExternalStorageDirectory().getPath() + "/" + System.currentTimeMillis() + "_compressPic.jpg";
			//调用压缩图片的方法，返回压缩后的图片path
			final String compressImage = ImageUtil.compressImage(file.getPath(), targetPath, 30);
			final File compressedPic = new File(compressImage);

			if (compressedPic.exists()) {
				Timber.d("图片压缩上传");
				file = compressedPic;
			} else {//直接上传
				//file = new File(path);
			}
		}

		CountingRequestBody countingRequestBody = new CountingRequestBody(requestBody, listener);
		MultipartBody.Part body = MultipartBody.Part.createFormData(fileArgName, file.getName(), countingRequestBody);

		//构建参数的part
		MediaType mediaType = MediaType.parse("multipart/form-data");
		Map<String, RequestBody> partMap = new TreeMap<>();

		for (Map.Entry<String, String> entry : args.entrySet()) {
			String key = entry.getKey();
			String val = entry.getValue();
			partMap.put(key, RequestBody.create(mediaType, val));
		}

		return getHttpRetrofitClient(API_URL, new HashMap<>(), HttpLoggingInterceptor.Level.BODY).create(BaseServerAPI.class).uploadFile(url, partMap, body);
	}

}
